﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MockSchoolManagement.Application;
using MockSchoolManagement.Core.Repositories;
using MockSchoolManagement.Domain.Students;
using MockSchoolManagement.Core;
using MockSchoolManagement.Mvc.ViewModel;

namespace MockSchoolManagement.Mvc.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        //private readonly IStudentRepository _studentRepository;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly IRepository<Student, int> _studentRepository;
        private readonly IStudentService _studentService;
        public HomeController(ILogger<HomeController> logger, IWebHostEnvironment webHostEnvironment,IRepository<Student,int> studentRepository, IStudentService studentService)
        {
            _logger = logger;
            _studentRepository = studentRepository;
            _studentService = studentService;
            _webHostEnvironment = webHostEnvironment;
        }

        public IActionResult TestAutoRegisterDi()
        {
            var result=_studentService.GetStudentByPage(1, 2);
            return Json(result);
        }

        public IActionResult Index()
        {
            IEnumerable<Student> model = _studentRepository.GetAllList();
            return View(model);
        }
        public IActionResult List()
        {
            IEnumerable<Student> model = _studentRepository.GetAllList();
            return View(model);
        }

        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Photos!=null&&model.Photos.Count>0)
                {
                    foreach (var photo in model.Photos)
                    {
                        string uploadFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images","avatar");
                        uniqueFileName = Guid.NewGuid() + "_" + photo.FileName;
                        string filePath = Path.Combine(uploadFolder, uniqueFileName);
                        photo.CopyTo(new FileStream(filePath, FileMode.Create));
                    }
                    
  
                }
                Student newStudent = new Student()
                {
                    Name = model.Name,
                    Email = model.Email,
                    PhotoPath = uniqueFileName
                };
                _studentRepository.Insert(newStudent);
                return RedirectToAction("Detial", new { id = newStudent.Id });
            }
            return View();
        }
        [HttpGet]
        public IActionResult Edit(int id)
        {
            var student= _studentRepository.FirstOrDefault(c=>c.Id==id);
            if (student==null)
            {
                //Response.StatusCode = 404;
                //return View("StudentNotFound", id);
                ViewBag.ErrorMessage = $"学生Id={id}的信息不存在";
                return View("NotFound");
            }

            StudentEditViewModel model = new StudentEditViewModel()
            {
                Id = student.Id,
                Email = student.Email,
                ExitingPhotoPath = student.PhotoPath,
                Name = student.Name

            };
            return View(model);

        }

        public IActionResult Detial(int id)
        { 
            _logger.LogTrace("Trace(跟踪)Log");
            _logger.LogDebug("Debug(调试)Log");
            _logger.LogInformation("信息（Information）Log");
            _logger.LogWarning("警告（Warning）Log");
            _logger.LogError("错误(Error)Log");
            _logger.LogCritical("严重(Critical)Log");
            //throw new Exception("在Detial视图出现了异常");
            var model = _studentRepository.FirstOrDefault(c=>c.Id==id);
            if (model == null)
            {
                //Response.StatusCode = 404;
                //return View("StudentNotFound", id);
                ViewBag.ErrorMessage = $"学生Id={id}的信息不存在，请重试.";
                return View("NotFound");
            }
            return View(model);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
